package logic

import (
	"errors"
	"fmt"
	"github.com/levigross/grequests"
	"regexp"
	"strings"
)

// GetDouYinVideoUrl 获取抖音视频地址
func GetDouYinVideoUrl(url string) (string, error) {
	realUrl1 := regexp.MustCompile(`(http.*://[^\s]*)`).FindStringSubmatch(url)
	if len(realUrl1) < 1 {
		return "", errors.New("请求抖音失败")
	}
	realUrl := realUrl1[1]
	// 先获取视频ID
	res, err := grequests.Get(realUrl, &grequests.RequestOptions{
		Headers: map[string]string{
			"Content-Type":                "application/json",
			"Access-Control-Allow-Origin": "*",
		},
	})
	if err != nil {
		return "", errors.New("请求抖音失败")
	}

	requrl := res.RawResponse.Request.URL.RequestURI()
	if len(requrl) < 10 {
		return "", errors.New("抖音视频地址获取失败")
	}

	itemid1 := regexp.MustCompile(`video/(.*?)\?`).FindStringSubmatch(requrl)
	if len(itemid1) < 1 {
		return "", errors.New("抖音视频获取失败")
	}

	itemid := itemid1[1]
	// 根据itemid获取原始视频
	original := "https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids=" + itemid

	res2, err := grequests.Get(original, &grequests.RequestOptions{
		Headers: map[string]string{
			"Content-Type":                "application/json",
			"Access-Control-Allow-Origin": "*",
		},
	})

	if err != nil {
		return "", errors.New("抖音视频获取失败")
	}

	vid1 := regexp.MustCompile(`vid":"(.*?)"`).FindStringSubmatch(res2.String())
	if len(vid1) < 1 {
		return "", errors.New("抖音视频获取失败")
	}
	vid := vid1[1]
	videoUrl := fmt.Sprintf("https://aweme.snssdk.com/aweme/v1/play/?video_id=%s&ratio=720p&line=0", vid)

	return videoUrl, nil
}

// getBilibiliVideoUrl 哔哩哔哩视频
func getBilibiliVideoUrl(url string) (string, error) {
	// 直接获取
	s := regexp.MustCompile(`(BV[0-9a-zA-Z]*)`).FindStringSubmatch(url)
	if len(s) != 2 {
		return "", errors.New("获取bilibili视频失败")
	}

	res, err := grequests.Get("https://m.bilibili.com/video/"+s[1], &grequests.RequestOptions{
		Headers: map[string]string{
			"Access-Control-Allow-Origin": "*",
			"Content-Type":                "application/json",
		},
		UserAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25",
	})

	if err != nil {
		return "", errors.New("请求bilibili视频失败")
	}
	regs := regexp.MustCompile(`readyVideoUrl: '(.*?)',`).FindStringSubmatch(res.String())
	if len(regs) != 2 {
		return "", errors.New("获取bilibili视频失败")
	}
	return regs[1], nil
}

// getEyePetizerVideoUrl 开眼视频
func getEyePetizerVideoUrl(url string) (string, error) {
	// video_id=209323 || resource_id=244837
	Itemid := regexp.MustCompile(`[vid,resource_id]=(.*)\d`).FindStringSubmatch(url)[1]
	return "https://baobab.kaiyanapp.com/api/v1/playUrl?vid=" + Itemid + "&resourceType=video&editionType=default&source=aliyun&playUrlType=url_oss&ptl=true", nil
}

//getMonMoVideoUrl 陌陌
func getMonMoVideoUrl(url string) (string, error) {
	// 直接获取
	s := regexp.MustCompile(`share-v2/(\w\w\d{1,})`).FindStringSubmatch(url)
	if len(s) != 2 {
		return "", errors.New("获取视频失败")
	}
	// data := Req{Feedids:[]string{s[1]}}
	res, err := grequests.Post("https://m.immomo.com/inc/microvideo/share/profiles", &grequests.RequestOptions{
		Headers: map[string]string{
			"Access-Control-Allow-Origin": "*",
			"Content-Type":                "application/json",
		},
		UserAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25",
		Params:    map[string]string{"feedids": s[1]},
	})

	if err != nil {
		return "", errors.New("获取视频失败")
	}
	// re.findall("playurl_video\":\"(.*?)\"",r.text)[0] 该接口已失效，videmo_url为空
	regs := regexp.MustCompile(`video_url":"(.*?)"`).FindStringSubmatch(res.String())
	if len(regs) != 2 {
		return "", errors.New("获取视频失败")
	}
	return regs[1], nil
}

// getKg3VideoUrl 全民k歌
func getKg3VideoUrl(url string) (string, error) {
	s := regexp.MustCompile(`s=(.*?)&`).FindStringSubmatch(url)
	if len(s) != 2 {
		return "", errors.New("获取视频失败")
	}

	res, err := grequests.Get("https://kg.qq.com/node/play?s="+s[1], &grequests.RequestOptions{
		Headers: map[string]string{
			"Access-Control-Allow-Origin": "*",
			"Content-Type":                "application/json",
		},
		UserAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25",
	})

	if err != nil {
		return "", errors.New("获取视频失败")
	}
	// re.findall("playurl_video\":\"(.*?)\"",r.text)[0]
	regs := regexp.MustCompile(`playurl_video":"(.*?)","poi_id`).FindStringSubmatch(res.String())
	if len(regs) != 2 {
		return "", errors.New("获取视频失败")
	}
	return regs[1], nil
}

// getKuaiShouVideoUrl 快手
func getKuaiShouVideoUrl(url string) (string, error) {
	res, err := grequests.Get(url, &grequests.RequestOptions{
		Headers: map[string]string{
			"Access-Control-Allow-Origin": "*",
			"Content-Type":                "application/json",
		},
		// Cookies: []*http.Cookie,
		UserAgent:    "Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25",
		UseCookieJar: true,
	})

	if err != nil {
		return "请求无效", errors.New("获取视频失败")
	}

	regs := regexp.MustCompile(`srcNoMark":"(.*?)"`).FindStringSubmatch(res.String())
	if len(regs) != 2 {
		return "", errors.New("获取视频失败")
	}
	return regs[1], nil
}

// getPiPixVideoUrl 皮皮虾
func getPiPixVideoUrl(url string) (string, error) {
	res, err := grequests.Get(url, &grequests.RequestOptions{
		Headers: map[string]string{
			"Content-Type":                "application/json",
			"Access-Control-Allow-Origin": "*",
		},
	})
	if err != nil {
		return "", errors.New("获取视频失败")
	}
	requrl := res.RawResponse.Request.URL.RequestURI() //
	// https://h5.pipix.com/item/6863294377570081027?app_id=1319&app=super&timestamp=1598011674&user_id=62108092335&carrier_region=cn&region=cn&language=zh&utm_source=weixin
	if len(requrl) < 10 {
		return "", errors.New("获取视频失败")
	}

	// Itemid := strings.Split(requrl, "/")[2] ///share/video/6734643996347485448/?region=CN&mid=6734637731277851404&u_code=0&titleType=title&utm_source=copy_link&utm_campaign=client_share&utm_medium=android&app=aweme
	// fmt.Println(res.RawResponse.Request.URL.RequestURI())
	reg := regexp.MustCompile(`item/(.*?)\?`) // ?号需要替
	Itemid := reg.FindStringSubmatch(res.RawResponse.Request.URL.RequestURI())[1]
	// fmt.Println(Itemid)
	// 根据ID然后获取原始视频

	infoUrl := "https://is.snssdk.com/bds/cell/detail/?cell_type=1&aid=1319&app_name=super&cell_id=" + Itemid
	res2, err := grequests.Get(infoUrl, &grequests.RequestOptions{
		Headers: map[string]string{
			"Content-Type":                "application/json",
			"Access-Control-Allow-Origin": "*",
		},
	})
	if err != nil {
		return "", errors.New("获取视频失败")
	}
	reg2 := regexp.MustCompile("origin_video_download.*?url_list.*?url.*?:\"(.*?)\"") // re.findall("origin_video_download.*?url_list.*?url.*?:\"(.*?)\"",r.text)
	videoUrl := reg2.FindStringSubmatch(res2.String())[1]                             // --》 /share/video/6734643996347485448/
	// fmt.Println(rr)
	return strings.ReplaceAll(videoUrl, `\u0026`, "&"), nil
}

// getWeiBoVideoUrl 微博
func getWeiBoVideoUrl(url string) (string, error) {
	Itemid := regexp.MustCompile(`(\d{1,}:\d{1,})`).FindStringSubmatch(url)[1]
	// 直接获取
	res, err := grequests.Get("https://video.h5.weibo.cn/s/video/object?object_id="+Itemid, &grequests.RequestOptions{
		Headers: map[string]string{
			"Access-Control-Allow-Origin": "*",
			"Content-Type":                "application/json",
		},
		UserAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25",
	})

	if err != nil {
		return "非法请求", errors.New("获取视频失败")
	}

	regs := regexp.MustCompile(`hd_url":"(.*?)"`).FindStringSubmatch(res.String())
	if len(regs) != 2 {
		return "", errors.New("获取视频失败")
	}
	return strings.ReplaceAll(regs[1], "\\", ""), nil
}

// getWeiShiVideoUrl 微视
func getWeiShiVideoUrl(url string) (string, error) {
	var Itemid string
	if strings.Contains(url, "h5.weishi") {
		res, err := grequests.Get(url, &grequests.RequestOptions{
			Headers: map[string]string{
				"Content-Type":                "application/json",
				"Access-Control-Allow-Origin": "*",
			},
		})
		if err != nil {
			return "", errors.New("获取视频失败")
		}
		requrl := res.RawResponse.Request.URL.RequestURI() //
		// https://h5.pipix.com/item/6863294377570081027?app_id=1319&app=super&timestamp=1598011674&user_id=62108092335&carrier_region=cn&region=cn&language=zh&utm_source=weixin
		if len(requrl) < 10 {
			return "", errors.New("获取视频失败")
		}

		Itemid = strings.Split(requrl, "/")[3] ///share/video/6734643996347485448/?region=CN&mid=6734637731277851404&u_code=0&titleType=title&utm_source=copy_link&utm_campaign=client_share&utm_medium=android&app=aweme
		// fmt.Println(Itemid)
	} else if strings.Contains(url, "isee.weishi") {
		// 自带参数
		Itemid = regexp.MustCompile("id=(.*?)&").FindStringSubmatch(url)[1]
	} else {
		return "", errors.New("获取视频失败")
	}

	// Itemid = Itemid[2]
	// fmt.Println(res.RawResponse.Request.URL.RequestURI())
	// reg := regexp.MustCompile(`item/(.*?)\?`) // ?号需要替
	// Itemid := reg.FindStringSubmatch(res.RawResponse.Request.URL.RequestURI())[1]
	// fmt.Println(Itemid)
	// 根据ID然后获取原始视频
	infourl := "https://h5.weishi.qq.com/webapp/json/weishi/WSH5GetPlayPage?feedid=" + Itemid
	res2, err := grequests.Get(infourl, &grequests.RequestOptions{
		Headers: map[string]string{
			"Content-Type":                "application/json",
			"Access-Control-Allow-Origin": "*",
		},
	})
	if err != nil {
		return "", errors.New("获取视频失败")
	}
	reg2 := regexp.MustCompile("video_url\":\"(.*?)\"") // re.findall("video_url\":\"(.*?)\"",r.text)[0]
	// fmt.Println(video_url)
	return reg2.FindStringSubmatch(res2.String())[1], nil
}

// getZuiYouVideo 最右
func getZuiYouVideo(url string) (string, error) {
	// 直接获取
	res, err := grequests.Get(strings.Replace(url, "post&", "post?", -1), &grequests.RequestOptions{
		Headers: map[string]string{
			"Access-Control-Allow-Origin": "*",
		},
		UserAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25",
	})

	if err != nil {
		return "", errors.New("获取视频失败")
	}
	// fmt.Println(res.String())
	regs := regexp.MustCompile(`playcnt":\d{1,},"url":"(.*?)"`).FindStringSubmatch(res.String())
	if len(regs) != 2 {
		return "", errors.New("获取视频失败")
	}
	return strings.ReplaceAll(regs[1], "\\u002F", "/"), nil
}
